import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { store } from "../store/index";
import LoginPage from "@/view/LoginPage.vue";
import BasePage from "@/view/BasicPage.vue";

const routes: Array<RouteRecordRaw> = [
  { path: "/", redirect: "/login" },
  {
    path: "/login",
    name: "Login",
    component: LoginPage,
  },
  {
    path: "/index",
    name: "Layout",
    redirect: "/welcome",
    component: BasePage,
    children: [
      {
        path: "/welcome",
        name: "WelcomePage",
        component: () => import("@/view/WelcomePage.vue"),
      },
      {
        path: "/roleManagement",
        name: "RoleManagement",
        component: () => import("@/view/system/RoleManagement.vue"),
      },
      {
        path: "/meunManagement",
        name: "MenuManagement",
        component: () => import("@/view/system/MenuManagement.vue"),
      },
      {
        path: "/usersList",
        name: "UsersList",
        component: () => import("@/view/system/UsersList.vue"),
      },
    ],
  },
];

const whiteList = ["/login"];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  if (whiteList.includes(to.path)) {
    next();
  } else {
    if (!token) {
      next({ path: "/login" });
    } else {
      if (!store.state.keepAlive.includes(to.name!.toString())) {
        store.commit("SET_KEEP_ALIVE", to.name);
      }
      next();
    }
  }
});

export default router;
